<?php

class Model_Game extends PhalApi_Model_NotORM
{
	// 添加游戏记录
	public function record($liveuid, $stream, $action, $time, $result, $bankerid, $bankercrad,$gameinfo=[])
	{
		// 获取游戏是否已经存在
		$game = DI()->notorm->game->select("*")->where('stream=? and state=0', $stream)->fetchOne();
		if($game){
			return 1000;
		}
		
		// 添加游戏信息
		$insert = array("liveuid" => $liveuid, "stream" => $stream, 'action' => $action, 'state' => '0', 'result' => $result, "starttime" => $time, "bankerid" => $bankerid, "banker_card" => $bankercrad,'gameinfo'=>json_encode($gameinfo, JSON_UNESCAPED_UNICODE));
		$rs     = DI()->notorm->game->insert($insert);
		if(!$rs){
			return 1001;
		}
		
		DI()->notorm->live->where('uid=?', $liveuid)->update(array("game_action" => $action));
		
		return $rs;
	}
	
	// 结束游戏
	public function endGame($liveuid, $gameid, $type, $ifset)
	{
		// 事务操作
		//$gameDb = DI()->notorm->game->lock();  // 这样会提示 已经 开启事务  There is already an active transaction
		//$gameDb = DI()->notorm->game;
		// 事务操作
		//DI()->notorm->transaction = 'BEGIN';
		DI()->notorm->beginTransaction('db_appapi');
		try{
			if($ifset == 1){
				DI()->notorm->live->where('uid=?', $liveuid)->update(array("game_action" => 0));
			}
			//		file_put_contents(API_ROOT.'/../log/phalapi/game_endGame_'.date('Y-m-d').'.txt',date('y-m-d H:i:s').' 提交参数信息 endGame:'.$liveuid.'--'.$gameid.'--'.$type."\r\n",FILE_APPEND);
			
			
			//$gameDb->lock();
			/*$sql    = 'SELECT * FROM cmf_game where id=? :start, :len';
			$params = array(':start' => 1, ':len' => 2);
			$rows   = DI()->notorm->game->queryAll($sql, $params);*/
			
			// 获取游戏信息
			//$game = DI()->notorm->game->select("*")->where('id=? and state=0', $gameid)->fetchOne();
			$game = DI()->notorm->game->lock()->select("*")->where('id=? and state=0', $gameid)->fetchOne();
			//$game = DI()->notorm->game->select("*")->where('id=? and state=0 FOR UPDATE', $gameid)->fetchOne();
			if(!$game){
				return 1000;
			}
			// 休息3秒钟
			//sleep(1);
			
			$addtime       = time();
			$giftid        = $game['id'];
			$action        = $game['action'];
			$result        = $game['result'];
			$bankerid      = $game['bankerid'];
			$banker_profit = 0;
			$isintervene   = 0;
			//file_put_contents(API_ROOT.'/../log/phalapi/game_endGame_'.date('Y-m-d').'.txt',date('Y-m-d H:i:s').' result:'.json_encode($result)."\r\n",FILE_APPEND);
			
			// 获取游戏牌面信息
			$gameToken = $game['stream']."_".$action."_".$game['starttime']."_Game";
			$gameinfo  = DI()->redis->Get($gameToken);
			//file_put_contents(API_ROOT.'/../log/phalapi/game_endGame_'.date('Y-m-d').'.txt',date('Y-m-d H:i:s').' redis里gameinfo:'.$gameinfo."\r\n",FILE_APPEND);
			$gameinfo = json_decode($gameinfo, 1);
			//DI()->logger->saveText($gameinfo,"redis里gameinfo牌面信息");
			DI()->redis->del($gameToken);
			
			// 结束类型，1为正常结束，2为主播关闭，3为意外断开
			// 非正常结束 将游戏投注返还给用户 + 返还庄家的下注
			if($type == 2 || $type == 3){
				$this->endGameAbnormalBet($action, $game);
				
				// 获取用户投注信息
				/*$total = DI()->notorm->gamerecord
					->select("uid,sum(coin_1 + coin_2 + coin_3 + coin_4 + coin_5 + coin_6) as total")->where('gameid=?', $gameid)->group('uid')->fetchAll();*/
				// 将用户投注记录返回给用户
				/*foreach($total as $k => $v){
					DI()->notorm->user->where('id = ?', $v['uid'])->update(array('coin' => new NotORM_Literal("coin + {$v['total']}"),));
					$insert = array(
						"type"      => '1',
						"action"    => '20',
						"uid"       => $v['uid'],
						"touid"     => $v['uid'],
						"giftid"    => $giftid,
						"giftcount" => 1,
						"totalcoin" => $v['total'],
						"showid"    => 0,
						"addtime"   => $addtime,
					);
					
					DI()->notorm->user_coinrecord->insert($insert);
				}*/
				
				/* 下庄处理 */
				// 返还庄家的下注
				//$action=4;
				/*if($action == 4){
					$key  = 'banker_'.$action.'_'.$game['stream'];
					$list = DI()->redis->hGetAll($key);
					foreach($list as $k => $v){
						$data = json_decode($v, true);
						$uid  = $k;
						DI()->notorm->user->where('id = ?', $uid)->update(array('coin' => new NotORM_Literal("coin + {$data['deposit']}"),));
						$addtime = time();
						$insert  = array(
							"type"      => '1',
							"action"    => '24',
							"uid"       => $uid,
							"touid"     => $uid,
							"giftid"    => 0,
							"giftcount" => 1,
							"totalcoin" => $data['deposit'],
							"showid"    => 0,
							"addtime"   => $addtime,
						);
						
						DI()->notorm->user_coinrecord->insert($insert);
					}
				}*/
			} else{
				// 正常结束游戏
				$win       = 0;
				$total_bet = DI()->notorm->gamerecord->where('gameid=?', $gameid)->sum("coin_1 + coin_2 + coin_3 + coin_4 + coin_5 + coin_6");
				if(!$total_bet){
					$total_bet = 0;
				}
				// 如果没有人下注 则不操作
				// 如果有人下注 则判断成功与失败
				$banker_profit = $total_bet;
				if($total_bet){
					$configpri = getConfigPri();
					$game_pump = $configpri['game_pump'];
					
					// 开心牛仔
					if($action == 4){
						$intervene = rand(0, 99);
						if($bankerid > 0){
							/* 用户坐庄 */
							if($intervene >= $configpri['game_odds_u']){
								$isintervene = 1;
							}
						} else{
							/* 平台坐庄 */
							if($intervene >= $configpri['game_odds_p']){
								$isintervene = 1;
							}
						}
						// 改变牌面大小
						if($isintervene){
							$data[1] = $gameinfo[0][9];
							$data[2] = $gameinfo[1][9];
							$data[3] = $gameinfo[2][9];
							$data[4] = $gameinfo[3][9];
							
							$pos = array_search(max($data), $data);
							if($pos != 4){
								/* 庄的牌面不是最大的 */
								$zhuang = $gameinfo[$pos - 1];
								$tihuan = $gameinfo[3];
								
								/* 调整数据 */
								$tihuan[7] = '1';
								$tihuan[8] = $zhuang[8];
								
								$zhuang[7] = '3';
								$zhuang[8] = '0';
								
								$gameinfo[$pos - 1] = $tihuan;
								$gameinfo[3]        = $zhuang;
							}
							
							$result = '1,1,1';
						}
						
						
						$coin = '';
						//file_put_contents(API_ROOT.'/../log/phalapi/game_endGame_'.date('Y-m-d').'.txt',date('y-m-d H:i:s').' 提交参数信息 game_result:'.json_encode($result)."\r\n",FILE_APPEND);
						$result_a = explode(",", $result);
						foreach($result_a as $k => $v){
							if($v == 3){
								if($coin == ''){
									$coin = "coin_".($k + 1);
								} else{
									$coin .= " + coin_".($k + 1);
								}
							}
						}
						//file_put_contents(API_ROOT.'/../log/phalapi/game_endGame_'.date('Y-m-d').'.txt',date('y-m-d H:i:s').' 提交参数信息 game_coin:'.json_encode($coin)."\r\n",FILE_APPEND);
						if($coin != ''){
							/* 有用户中奖 */
							$total = DI()->notorm->gamerecord
								->select("uid,liveuid,sum({$coin}) as total")->where('gameid=?', $gameid)->group('uid')->fetchAll();
							//file_put_contents(API_ROOT.'/../log/phalapi/game_endGame_'.date('Y-m-d').'.txt',date('y-m-d H:i:s').' 提交参数信息 total:'.json_encode($total)."\r\n",FILE_APPEND);
							foreach($total as $k => $v){
								$gamecoin = $v['total'] + floor($v['total'] * (100 - $game_pump) * 0.01);
								//file_put_contents(API_ROOT.'/../log/phalapi/game_endGame_'.date('Y-m-d').'.txt',date('y-m-d H:i:s').' 提交参数信息 gamecoin:'.json_encode($gamecoin)."\r\n",FILE_APPEND);
								
								$win += $v['total'] * 2;
								//DI()->notorm->user->where('id = ?', $v['uid'])->update(array('score' => new NotORM_Literal("score + {$gamecoin}"),));
								DI()->notorm->user->where('id = ?', $v['uid'])->update(array('coin' => new NotORM_Literal("coin + {$gamecoin}"),));
								$insert = array(
									"type"        => '1',
									"action"      => '21',
									"uid"         => $v['uid'],
									"touid"       => $v['liveuid'],
									"giftid"      => $giftid,
									"giftcount"   => 1,
									"totalcoin"   => $gamecoin,
									"addtime"     => $addtime,
									"game_action" => $action,
								);
								
								DI()->notorm->user_scorerecord->insert($insert);
							}
							//file_put_contents(API_ROOT.'/../log/phalapi/game_endGame_'.date('Y-m-d').'.txt',date('y-m-d H:i:s').' 提交参数信息 win:'.json_encode($win)."\r\n",FILE_APPEND);
							$banker_profit -= $win;
							
							//file_put_contents(API_ROOT.'/../log/phalapi/game_endGame_'.date('Y-m-d').'.txt',date('y-m-d H:i:s').' 提交参数信息 banker_profit:'.json_encode($banker_profit)."\r\n",FILE_APPEND);
						}
						/* 更新庄家信息 */
						if($bankerid > 0){
							/* 用户上庄 更新 缓存信息 不更新数据库 */
							$stream     = $game['stream'];
							$key        = 'banker_'.$action.'_'.$stream;
							$isexist    = DI()->redis->hGet($key, $bankerid);
							$bankerinfo = json_decode($isexist, 1);
							
							$bankerinfo['deposit'] = $bankerinfo['deposit'] + $banker_profit;
							$bankerinfo['coin']    = NumberFormat($bankerinfo['deposit']);
							
							DI()->redis->hSet($key, $bankerid, json_encode($bankerinfo));
						} else{
							DI()->notorm->live
								->where('uid = ?', $liveuid)
								->update(array('banker_coin' => new NotORM_Literal("banker_coin + {$banker_profit}")));
						}
					} else{
						/* 其他游戏 */
						$data      = array();
						$game_odds = $configpri['game_odds'];
						$is_open   = isset($configpri['platform_total_amount_switch']) ? $configpri['platform_total_amount_switch'] : 0;  // 是否开启水池
						$intervene = rand(0, 99);    //  干预随机数（0-99）
						
						// 如果开启水池
						if($is_open){
							// 获取平台设置百分比的值
							$platform_total_name = 'platform_total_amount';
							$platform_total_info = DI()->notorm->site_config->select("*")->where('name=?', $platform_total_name)->fetchOne();
							// 干预结果的各种数据
							//$game_odds = 100;   // 干预比例
							$game_odds = $this->getPlatformPercent($platform_total_info['config']);
							DI()->logger->saveText('----------------------------------------------------------');
							DI()->logger->saveText('干预比例：'.$intervene." 对比比例：".$game_odds." 水池名称：".$platform_total_name." 水池值：".$platform_total_info['config']);
						}else{
							DI()->logger->saveText('----------------------------------------------------------');
							DI()->logger->saveText('干预比例：'.$intervene." 对比比例：".$game_odds." 水池：未开启");
						}

						
						// 如果执行干预
						if($intervene < abs($game_odds)){
							// TODO 干预结果判断
							//   1、随机比例判断
							//   2、投注金额判断：（投注大的不能用）
							//     获取每个投注金额
							$isintervene = 1;
							/*$field   = "sum(coin_1) as total_1, sum(coin_2) as total_2, sum(coin_3) as total_3";
							$sum_bet = DI()->notorm->gamerecord->where('gameid=?', $gameid)->select($field)->group('gameid')->fetchAll();
							if($sum_bet){
								$_bet    = $sum_bet[0];
								$max_bet = max($_bet);
								$res_bet = $_bet['total_'.$result];
								
								// 需要干预牌结果的时候 展示牌信息
								DI()->logger->saveText($sum_bet, '下注信息');
								DI()->logger->saveText($gameinfo, '当前牌信息');
								DI()->logger->saveText('数据库 不是redis 最大投注：'.$max_bet." 最大牌位的投注：".$res_bet." 最大牌位：".$result);
								// 是否干预
								// 判断最大位置与最大投注位置 相同则干预
								if($res_bet < $max_bet){
									$isintervene = 1;
									DI()->logger->saveText('=====>执行干预');
								} else{
									$isintervene = 0;
									DI()->logger->saveText('=====>不干预');
								}
							}*/
						}
						
						// 干预游戏结果
						if($isintervene){
							/* 进行干预 */
							if($action == 1){
								// 炸金花游戏
								$data[1] = $gameinfo[0][5];
								$data[2] = $gameinfo[1][5];
								$data[3] = $gameinfo[2][5];
							} elseif($action == 2){
								$data[1] = $gameinfo[0][8];
								$data[2] = $gameinfo[1][8];
								$data[3] = $gameinfo[2][8];
							} elseif($action == 3){
								$data[1] = $gameinfo[1];
								$data[2] = $gameinfo[2];
								$data[3] = $gameinfo[3];
								$data[4] = $gameinfo[4];
							} elseif($action == 4){
								$data[1] = $gameinfo[0][8];
								$data[2] = $gameinfo[1][8];
								$data[3] = $gameinfo[2][8];
							} elseif($action == 5){
								$data[1] = $gameinfo[0][5];
								$data[2] = $gameinfo[1][5];
								$data[3] = $gameinfo[2][5];
							}
							
							// 炸金花游戏
							if($action == 1){
								// 使用自带redis缓存
								//$pos = array_search(min($data), $data);  // 获取得到最小位置的投注 返回的是键值
								
								// 根据投注数量 获取赢钱输钱的位置
								$_value = isset($platform_total_info['config'])?$platform_total_info['config']:0; // 水池值
								$pos = $this->getJinhuaPosByBet($data, $_value, $result, $game_odds);
								
								// 不 使用自带redis缓存
								//$pos = $result == 1 ? 2 : 1;  // 这个是上面已经获取得到投注比较的操作
							} else{
								$pos = array_search(min($data), $data);
							}
							
							// 使用自带redis缓存
							DI()->logger->saveText("干预牌结果前：redis 投注数据".json_encode($data));
							DI()->logger->saveText("干预牌结果前：redis 牌数据".json_encode($gameinfo, JSON_UNESCAPED_UNICODE));
							DI()->logger->saveText(" 修改后投注位置".$pos." 最大牌位置 ".$result);
							DI()->logger->saveText(" 修改后位置投注".$data[$pos]." 最大牌数投注 ".$data[$result]);
							if($pos != $result){
								DI()->logger->saveText('=====>执行干预');
								/* 当前中奖位置不是下注最少的位置 */
								if($action == 1){
									$max                   = $gameinfo[$result - 1];
									$gameinfo[$result - 1] = $gameinfo[$pos - 1];
									$gameinfo[$pos - 1]    = $max;
									$result                = $pos;
								} elseif($action == 2){
									if($pos != 2 && $result != 2){
										$max                   = $gameinfo[$result - 1];
										$gameinfo[$result - 1] = $gameinfo[$pos - 1];
										$gameinfo[$pos - 1]    = $max;
										$result                = $pos;
									}
								} elseif($action == 3){
									$max = $gameinfo[$result];
									//file_put_contents(API_ROOT.'/../log/phalapi/game_endGame_'.date('Y-m-d').'.txt',date('Y-m-d H:i:s').' 进行干预后取最大值:'.json_encode($max)."\r\n",FILE_APPEND);
									$gameinfo[$result] = $gameinfo[$pos];
									//file_put_contents(API_ROOT.'/../log/phalapi/game_endGame_'.date('Y-m-d').'.txt',date('Y-m-d H:i:s').' 将最大值替换为最小值:'.$result.''.json_encode($gameinfo[$pos])."\r\n",FILE_APPEND);
									$gameinfo[$pos] = $max;
									//file_put_contents(API_ROOT.'/../log/phalapi/game_endGame_'.date('Y-m-d').'.txt',date('Y-m-d H:i:s').' 将最小值替换为最大值:'.$pos.''.json_encode($max)."\r\n",FILE_APPEND);
									$result = $pos;
									
									//file_put_contents(API_ROOT.'/../log/phalapi/game_endGame_'.date('Y-m-d').'.txt',date('Y-m-d H:i:s').' 替换result:'.$result.''.json_encode($pos)."\r\n",FILE_APPEND);
								} elseif($action == 4){
									$max                   = $gameinfo[$result - 1];
									$gameinfo[$result - 1] = $gameinfo[$pos - 1];
									$gameinfo[$pos - 1]    = $max;
									$result                = $pos;
								} elseif($action == 5){
									$max                   = $gameinfo[$result - 1];
									$gameinfo[$result - 1] = $gameinfo[$pos - 1];
									$gameinfo[$pos - 1]    = $max;
									$result                = $pos;
								}
								
								
								// 需要干预牌结果的时候 展示牌信息
								DI()->logger->saveText($gameinfo, '需要干预牌结果后：牌面信息');
								DI()->logger->saveText('干预牌结果后：'." 最大牌位置 ".$result);
							} else{
								DI()->logger->saveText('=====>不 干预');
							}
						}
						
						// 获取游戏下注信息
						$coin  = "coin_".$result;
						$total = DI()->notorm->gamerecord->select("uid,liveuid,sum({$coin}) as total")->where('gameid=?', $gameid)->group('uid')->fetchAll();
						
						// 如果是 炸金花
						$is_dan = 0;
						if($action == 1){
							// 单牌 2.8倍
							// 其他 3倍
							$is_dan = $gameinfo[($result - 1)][4] == '单牌';
							//file_put_contents(API_ROOT.'/../log/phalapi/game_endGame_'.date('Y-m-d').'.txt', date('y-m-d H:i:s').' 提交参数信息 card:'.json_encode($gameinfo)." result: ".$result." is_dan:".$is_dan." 单牌:".$gameinfo[($result-1)][4]."\r\n", FILE_APPEND);
						}
						
						// 给每个下注的返回下注奖励
						foreach($total as $k => $v){
							
							// 如果是 炸金花 盈利
							if($action == 1){
								// 单牌 2.8倍
								if($is_dan){
									//$gamecoin = floor($v['total'] * 2.8);
									//$win      += $v['total'] * 2.8;
									
									/*$gamecoin = floor($v['total'] * 2.97);
									$win      += $v['total'] * 2.97;*/
									
									$gamecoin = floor($v['total'] * 2.9);
									$win      += $v['total'] * 2.9;
								} else{
									// 其他 3倍
									$gamecoin = floor($v['total'] * 3);
									$win      += $v['total'] * 3;
								}
							} else{
								// 一般情况的获取 盈利
								$gamecoin = $v['total'] + floor($v['total'] * (100 - $game_pump) * 0.01);
								$win      += $v['total'] * 2;
							}
							
							
							// 更新用户钻石信息
							//file_put_contents(API_ROOT.'/../log/phalapi/game_endGame_'.date('Y-m-d').'.txt', date('y-m-d H:i:s').' 提交参数信息 gamecoin:'.json_encode($gamecoin)." total: ".$v['total']."\r\n", FILE_APPEND);
							//DI()->notorm->user->where('id = ?', $v['uid'])->update(array('score' => new NotORM_Literal("score + {$gamecoin}"),));
							DI()->notorm->user->where('id = ?', $v['uid'])->update(array('coin' => new NotORM_Literal("coin + {$gamecoin}"),));
							
							// 添加游戏获奖记录
							$insert = array(
								"type"        => '1',
								"action"      => '21',
								"uid"         => $v['uid'],
								"touid"       => $v['liveuid'],
								"giftid"      => $giftid,
								"giftcount"   => 1,
								"totalcoin"   => $gamecoin,
								"addtime"     => $addtime,
								"game_action" => $action,
							);
							
							DI()->notorm->user_scorerecord->insert($insert);
						}
						$banker_profit -= $win;
					}
				}
				
			}
			
			// 删除游戏信息
			$gameToken = $game['stream']."_".$game['action']."_".$game['starttime']."_Game";
			DI()->redis->del($gameToken);
			
			// 更新游戏状态
			$update = array(
				'state'         => $type,
				'result'        => $result,
				'banker_profit' => $banker_profit,
				'isintervene'   => $isintervene,
				'endtime'       => time(),
			);
			DI()->notorm->game->where('id = ? and liveuid =?', $gameid, $liveuid)->update($update);
			DI()->notorm->gamerecord->where('gameid=?', $gameid)->update(array('status' => '1'));
			if($game['action'] == 3){
				$gameinfo[0] = $result;
			}
			
			// 更新平台设置的金额
			if($total_bet){
				DI()->logger->saveText('总共投注：'.$total_bet." 赢钱：".$win." 差异".$banker_profit);
			}
			if(!empty($is_open)){
				$this->updatePlatformBetNumber($banker_profit);
			}
		
			
			// 休息3秒钟
			//sleep(1);
			
			//file_put_contents(API_ROOT.'/../log/phalapi/game_endGame_'.date('Y-m-d').'.txt',date('Y-m-d H:i:s').' 返回gameinfo:'.json_encode($gameinfo)."\r\n\r\n",FILE_APPEND);
			
			//DI()->notorm->transaction = 'COMMIT';
			DI()->notorm->commit('db_appapi');
		} catch(\Exception $e){
			// 回滚事务
			//DI()->notorm->transaction = 'ROLLBACK';
			DI()->notorm->rollback('db_appapi');
			
			DI()->logger->saveText('结束游戏错误：'.$e->getMessage());
			//$res['message'] = $e->getMessage();
			//return $gameinfo;
		}
		
		return $gameinfo;
	}
	
	// 下注
	public function gameBet($uid, $gameid, $coin, $action, $grade)
	{
		$game = DI()->notorm->game->lock()->select("*")->where('id=?', $gameid)->fetchOne();
		//        file_put_contents(API_ROOT.'/../log/phalapi/game_gameBet_'.date('Y-m-d').'.txt',date('Y-m-d H:i:s').' 提交参数信息 uid:'.json_encode($uid)."\r\n",FILE_APPEND);
		//        file_put_contents(API_ROOT.'/../log/phalapi/game_gameBet_'.date('Y-m-d').'.txt',date('Y-m-d H:i:s').' 提交参数信息 gameid:'.json_encode($gameid)."\r\n",FILE_APPEND);
		//        file_put_contents(API_ROOT.'/../log/phalapi/game_gameBet_'.date('Y-m-d').'.txt',date('Y-m-d H:i:s').' 提交参数信息 coin:'.json_encode($coin)."\r\n",FILE_APPEND);
		//        file_put_contents(API_ROOT.'/../log/phalapi/game_gameBet_'.date('Y-m-d').'.txt',date('Y-m-d H:i:s').' 提交参数信息 action:'.json_encode($action)."\r\n",FILE_APPEND);
		//        file_put_contents(API_ROOT.'/../log/phalapi/game_gameBet_'.date('Y-m-d').'.txt',date('Y-m-d H:i:s').' 提交参数信息 grade:'.json_encode($grade)."\r\n",FILE_APPEND);
		//        file_put_contents(API_ROOT.'/../log/phalapi/game_gameBet_'.date('Y-m-d').'.txt',date('Y-m-d H:i:s').' 提交参数信息 game:'.json_encode($game)."\r\n",FILE_APPEND);
		if(!$game || $game['state'] != "0"){
			return 1001;
		}
		
		$bankerid = $game['bankerid'];
		/* 下注总额 */
		
		$total = DI()->notorm->gamerecord
			->where('action = ? and uid=? and gameid=? and liveuid=?', $action, $uid, $gameid, $game['liveuid'])
			->sum("coin_1 + coin_2 + coin_3 + coin_4 + coin_5 + coin_6");
		//file_put_contents(API_ROOT.'/../log/phalapi/game_gameBet_'.date('Y-m-d').'.txt',date('Y-m-d H:i:s').' 提交参数信息 total1:'.json_encode($total)."\r\n",FILE_APPEND);
		
		// 判断用户下注金额是否太多
		$total = $total + $coin;
		//file_put_contents(API_ROOT.'/../log/phalapi/game_gameBet_'.date('Y-m-d').'.txt',date('Y-m-d H:i:s').' 提交参数信息 total2:'.json_encode($total)."\r\n",FILE_APPEND);
		if($bankerid > 0){
			/* 用户上庄，下注金额不能大于庄家押金 */
			$total_all    = DI()->notorm->gamerecord
				->where('action = ? and gameid=? and liveuid=?', $action, $gameid, $game['liveuid'])
				->sum("coin_1 + coin_2 + coin_3 + coin_4 + coin_5 + coin_6");
			$total_all    = $total_all + $coin;
			$key          = 'banker_'.$action.'_'.$game['stream'];
			$bankerinfo   = DI()->redis->hget($key, $bankerid);
			$bankerinfo_a = json_decode($bankerinfo, 1);
			if($total_all > $bankerinfo_a['deposit']){
				return 1003;
			}
		}
		if($total > 500000){
			return 1003;
		}
		
		// 事务操作
		/*DI()->notorm->transaction = 'BEGIN';
		$userDb = DI()->notorm->user;
		DI()->notorm->transaction = 'BEGIN';
		try{
			$userDb->lock();
			
			DI()->notorm->transaction = 'COMMIT';
		} catch(\Exception $e){
			// 回滚事务
			DI()->notorm->transaction = 'ROLLBACK';
			
			$res['message'] = $e->getMessage();
			return $res;
		}*/
		
		
		// 判断用户金币是否足够
		$ifok = DI()->notorm->user->where('id = ? and coin >=?', $uid, $coin)->update(array('coin' => new NotORM_Literal("coin - {$coin}"), 'consumption' => new NotORM_Literal("consumption + {$coin}"),));
		//file_put_contents(API_ROOT.'/../log/phalapi/game_gameBet_'.date('Y-m-d').'.txt',date('Y-m-d H:i:s').' 提交参数信息 ifok:'.json_encode($ifok)."\r\n",FILE_APPEND);
		if(!$ifok){
			return 1000;
		}
		
		// 判断该用户是否已经下注
		$gamerecord = DI()->notorm->gamerecord->select('id')->where('action = ? and uid=? and gameid=? and liveuid=?', $action, $uid, $gameid, $game['liveuid'])->fetchOne();
		//file_put_contents(API_ROOT.'/../log/phalapi/game_gameBet_'.date('Y-m-d').'.txt',date('Y-m-d H:i:s').' 提交参数信息 gamerecord:'.json_encode($gamerecord)."\r\n",FILE_APPEND);
		$field = 'coin_'.$grade;
		if($gamerecord){
			// 如果已经下注 则继续增加游戏下注金额
			$users_game = DI()->notorm->gamerecord
				->where('id = ? ', $gamerecord['id'])
				->update(array($field => new NotORM_Literal("{$field} + {$coin}")));
			//file_put_contents(API_ROOT.'/../log/phalapi/game_gameBet_'.date('Y-m-d').'.txt',date('Y-m-d H:i:s').' 提交参数信息 更新 field:'.json_encode($field). '----coin:'.json_encode($coin)."\r\n",FILE_APPEND);
		} else{
			// 如果用户没有下注 则添加游戏下注记录
			$insert     = array(
				"action"  => $action,
				"uid"     => $uid,
				'gameid'  => $gameid,
				'liveuid' => $game['liveuid'],
				$field    => $coin,
				"addtime" => time(),
			);
			$users_game = DI()->notorm->gamerecord->insert($insert);
			//file_put_contents(API_ROOT.'/../log/phalapi/game_gameBet_'.date('Y-m-d').'.txt',date('Y-m-d H:i:s').' 提交参数信息 新增 field:'.json_encode($field). '----coin:'.json_encode($coin)."\r\n",FILE_APPEND);
		}
		
		//file_put_contents(API_ROOT.'/../log/phalapi/game_gameBet_'.date('Y-m-d').'.txt',date('Y-m-d H:i:s').' 提交参数信息 users_game:'.json_encode($users_game)."\r\n",FILE_APPEND);
		if(!$users_game){
			return 1002;
		}
		
		
		// 添加游戏下注后：用户金币变化记录
		$addtime = time();
		$giftid  = $game['id'];
		$insert  = array(
			"type"      => '0',
			"action"    => '19',
			"uid"       => $uid,
			"touid"     => $uid,
			"giftid"    => $giftid,
			"giftcount" => 1,
			"totalcoin" => $coin,
			"addtime"   => $addtime,
		);
		
		DI()->notorm->user_coinrecord->insert($insert);
		$info = DI()->notorm->user->select('coin')->where('id = ?', $uid)->fetchOne();
		
		$rs['uid']      = $uid;
		$rs['coin']     = $info['coin'];
		$rs['gametime'] = $game['starttime'];
		$rs['stream']   = $game['stream'];
		
		return $rs;
	}
	
	
	public function checkGame($liveuid, $stream, $uid)
	{
		$rs   = array(
			"brand"         => array(),
			"bet"           => array('0', '0', '0', '0'),
			"time"          => "0",
			"id"            => "0",
			"action"        => "0",
			"bankerid"      => "0",
			"banker_name"   => "吕布",
			"banker_avatar" => "",
			"banker_coin"   => "0",
		);
		$game = DI()->notorm->game->select("*")->where('liveuid=? and stream=? and state=?', $liveuid, $stream, 0)->fetchOne();
		if($game){
			$action     = $game["action"];
			$brandToken = $stream."_".$action."_".$game['starttime']."_Game";
			$brand      = DI()->redis->get($brandToken);
			$brand      = json_decode($brand, 1);
			$data       = array();
			if($action == 1){
				$data[] = $brand[0][5];
				$data[] = $brand[1][5];
				$data[] = $brand[2][5];
			} elseif($action == 2){
				$data[] = $brand[0][8];
				$data[] = $brand[1][8];
				$data[] = $brand[2][8];
			} elseif($action == 3){
				$data[] = $brand[1];
				$data[] = $brand[2];
				$data[] = $brand[3];
				$data[] = $brand[4];
			} elseif($action == 4){
				$data[] = $brand[0][8];
				$data[] = $brand[1][8];
				$data[] = $brand[2][8];
			} elseif($action == 5){
				$data[] = $brand[0][5];
				$data[] = $brand[1][5];
				$data[] = $brand[2][5];
			}
			
			$rs['brand'] = $data;
			$time        = 30 - (time() - $game['starttime']) + 3;
			if($time < 0){
				$time = "0";
			}
			$rs['time']     = (string)$time;
			$rs['id']       = (string)$game["id"];
			$rs['bankerid'] = (string)$game["bankerid"];
			
			if($game["bankerid"] > 0){
				$key     = 'banker_'.$action.'_'.$stream;
				$isexist = DI()->redis->hGet($key, $game["bankerid"]);
				
				$bankerinfo          = json_decode($isexist, 1);
				$rs['banker_name']   = $bankerinfo['user_nickname'];
				$rs['banker_avatar'] = $bankerinfo['avatar'];
				$rs['banker_coin']   = $bankerinfo['coin'];
			} else{
				$userinfo          = DI()->notorm->live->select("banker_coin")->where('uid=?', $liveuid)->fetchOne();
				$rs['banker_coin'] = NumberFormat($userinfo['banker_coin']);
			}
			
			$rs['action'] = (string)$action;
			/* DI()->redis  -> set($BetToken,json_encode($data)); */
			
			/* 用户下注信息 */
			$userbet = DI()->notorm->gamerecord
				->select("sum(coin_1) as bet1,sum(coin_2) as bet2,sum(coin_3) as bet3,sum(coin_4) as bet4")
				->where('gameid=? and uid=?', $game['id'], $uid)->fetchOne();
			if($userbet['bet1']){
				$rs['bet'][0] = $userbet['bet1'];
			}
			if($userbet['bet2']){
				$rs['bet'][1] = $userbet['bet2'];
			}
			if($userbet['bet3']){
				$rs['bet'][2] = $userbet['bet3'];
			}
			if($userbet['bet4']){
				$rs['bet'][3] = $userbet['bet4'];
			}
		} else{
			$userinfo          = DI()->notorm->live->select("banker_coin")->where('uid=?', $liveuid)->fetchOne();
			$rs['banker_coin'] = NumberFormat($userinfo['banker_coin']);
		}
		
		return $rs;
	}
	
	//  计算用户收益（收益在结束游戏的时候已经下发给各个游戏玩家）
	public function settleGame($uid, $gameid)
	{
		// 判断游戏是否已经结束
		$game = DI()->notorm->game->select("*")->where('id=?  and state!=0', $gameid)->fetchOne();
		if(!$game){
			return 1000;
		}
		
		// 获取用户的下注总金额
		$total    = DI()->notorm->gamerecord->where('gameid=? and uid=?', $gameid, $uid)->sum('coin_1 + coin_2 + coin_3 + coin_4 ');
		$action   = $game['action'];
		$result   = $game['result'];
		$bankerid = $game['bankerid'];
		$game_win = 0;
		
		// 如果有下注 则获取用户下注得到的积分
		if($total){
			$coinrecord = DI()->notorm->user_scorerecord
				->select("totalcoin")->where('action=21 and uid=? and giftid=?', $uid, $gameid)->fetchOne();
			if($coinrecord){
				$game_win = $coinrecord['totalcoin'];
			}
		} else{
			$total = 0;
		}
		//file_put_contents(API_ROOT.'/../log/phalapi/game_settleGame_'.date('Y-m-d').'.txt',date('y-m-d H:i:s').' 提交参数信息 game_win:'.json_encode($game_win)."\r\n",FILE_APPEND);
		/* if($action==4){
			$total_win=$game_win-$total;
			if($total_win>=0){
				$total_win='+'.$total_win;
			}
		}else{
			$total_win=$game_win;
		} */
		//$settle['gameinfo'] = json_decode($game['gameinfo'],true);
		$settle['gamecoin'] = (string)$game_win;
		$banker_profit      = $game['banker_profit'];
		if($banker_profit >= 0){
			$banker_profit = '+'.$banker_profit;
		}
		
		// 组合返回信息
		$settle['banker_profit'] = (string)$banker_profit;
		$settle['bankerid']      = $bankerid;
		$settle['isshow']        = '0';
		
		// 如果是庄家 庄家处理 则进行下庄处理
		$stream  = $game['stream'];
		$key     = 'banker_'.$action.'_'.$stream;
		$isexist = DI()->redis->hGet($key, $uid);
		if($isexist){
			$configpri  = getConfigPri();
			$bankerinfo = json_decode($isexist, 1);
			if($bankerinfo['isout'] == 1){
				/* 手动下庄 */
				$this->quietBanker($uid, $bankerinfo);
				DI()->redis->hdel($key, $uid);
			} elseif($bankerinfo['deposit'] < $configpri['game_banker_limit']){
				/* 自动下庄 */
				$settle['isshow'] = '1';
				$this->quietBanker($uid, $bankerinfo);
				DI()->redis->hdel($key, $uid);
			}
		}
		
		// 获取用户的总钻石金额
		$userinfo       = DI()->notorm->user->select("coin")->where('id=?', $uid)->fetchOne();
		$coin           = $userinfo['coin'] + $total;
		$settle['coin'] = (string)$userinfo['coin'];
		
		//DI()->notorm->user->where('id=?', $uid)->update(['coin'=>$coin]);
		
		//file_put_contents(API_ROOT.'/../log/phalapi/game_settleGame_'.date('Y-m-d').'.txt',date('y-m-d H:i:s').' 提交参数信息 settle:'.json_encode($settle)."\r\n\r\n",FILE_APPEND);
		
		//DI()->logger->saveText($gameinfo,"结算返回的牌面信息");
		DI()->logger->saveText($settle,"结算返回的结算信息");
		
		
		return $settle;
	}
	
	/* 游戏记录 */
	public function getGameRecord($action, $stream)
	{
		$result = array();
		$list   = DI()->notorm->game
			->select("action,result")->where('action=? and stream=? and state=1', $action, $stream)
			->order("starttime desc")->limit(0, 50)->fetchAll();
		
		foreach($list as $k => $v){
			$rs = array('0', '0', '0');
			if($action == 3){
				$rs = array('0', '0', '0', '0');
			}
			if($action == 4){
				$result_a = explode(",", $v['result']);
				foreach($result_a as $_k => $_v){
					if($_v == 3){
						$rs[$k] = '1';
					}
				}
			} else{
				$rs[$v['result'] - 1] = '1';
			}
			
			$result[] = $rs;
		}
		
		return $result;
	}
	
	/* 庄家流水 */
	public function getBankerProfit($bankerid, $action, $stream)
	{
		$list = DI()->notorm->game
			->select("banker_profit,banker_card")
			->where('bankerid=? and action=? and stream=? and state=1', $bankerid, $action, $stream)
			->order("starttime desc")->limit(0, 30)->fetchAll();
		
		return $list;
	}
	
	/* 平台庄家 */
	public function getBanker($stream)
	{
		$gamerecord = DI()->notorm->live->select("banker_coin")->where('stream=? ', $stream)->fetchOne();
		if($gamerecord){
			$platform_coin = NumberFormat($gamerecord['banker_coin']);
		} else{
			$platform_coin = NumberFormat(10000000);
		}
		
		$rs = array(
			'id'            => '0',
			'user_nickname' => '吕布',
			'avatar'        => '',
			'coin'          => $platform_coin,
		);
		
		return $rs;
	}
	
	/* 上庄 */
	public function setBanker($uid)
	{
		$userinfo = DI()->notorm->user->select("id,user_nickname,avatar,coin")->where('id=?', $uid)->fetchOne();
		if($userinfo){
			$userinfo['avatar'] = get_upload_path($userinfo['avatar']);
		}
		
		return $userinfo;
	}
	
	/* 扣除押金 */
	public function setDeposit($uid, $deposit)
	{
		// 个人押金
		$update = array('coin' => new NotORM_Literal("coin - {$deposit}"));
		DI()->notorm->user->where('id = ? and coin >=?', $uid, $deposit)->update($update);
		
		// 添加记录
		$addtime = time();
		$insert  = array(
			"type"      => '0',
			"action"    => '23',
			"uid"       => $uid,
			"touid"     => $uid,
			"giftid"    => 0,
			"giftcount" => 1,
			"totalcoin" => $deposit,
			"addtime"   => $addtime,
			//"game_action" => 4,
			"action"    => 14,  // 14：缴纳保证金
		);
		
		DI()->notorm->user_coinrecord->insert($insert);
		
		$info = DI()->notorm->user->select('coin')->where('id = ?', $uid)->fetchOne();
		
		return $info;
	}
	
	/* 下庄 */
	public function quietBanker($uid, $data)
	{
		//file_put_contents(API_ROOT.'/../log/phalapi/game_quietBanker_'.date('Y-m-d').'.txt',date('y-m-d H:i:s').' 提交参数信息 :'.json_encode($data)."\r\n",FILE_APPEND);
		// 更新
		$update = array('coin' => new NotORM_Literal("coin + {$data['deposit']}"));
		DI()->notorm->user->where('id = ?', $uid)->update($update);
		
		// 添加
		$addtime = time();
		$insert  = array(
			"type"        => '1',
			"action"      => '24',
			"uid"         => $uid,
			"touid"       => $uid,
			"giftid"      => 0,
			"giftcount"   => 1,
			"totalcoin"   => $data['deposit'],
			"showid"      => 0,
			"addtime"     => $addtime,
			"game_action" => 4,
			"game_banker" => 0,
		);
		
		DI()->notorm->user_coinrecord->insert($insert);
		
		return 1;
	}
	
	
	// 非正常结束游戏操作：钻石下注处理
	protected function endGameAbnormalBet($action, $game)
	{
		$giftid  = $game['id'];
		$gameid  = $game['id'];
		$addtime = time();
		// 获取用户投注信息
		$total = DI()->notorm->gamerecord
			->select("uid,sum(coin_1 + coin_2 + coin_3 + coin_4 + coin_5 + coin_6) as total")->where('gameid=?', $gameid)->group('uid')->fetchAll();
		// 将用户投注记录返回给用户
		foreach($total as $k => $v){
			DI()->notorm->user->where('id = ?', $v['uid'])->update(array('coin' => new NotORM_Literal("coin + {$v['total']}"),));
			$insert = array(
				"type"      => '1',
				"action"    => '20',
				"uid"       => $v['uid'],
				"touid"     => $v['uid'],
				"giftid"    => $giftid,
				"giftcount" => 1,
				"totalcoin" => $v['total'],
				"showid"    => 0,
				"addtime"   => $addtime,
			);
			
			DI()->notorm->user_coinrecord->insert($insert);
		}
		
		/* 下庄处理 */
		// 返还庄家的下注
		//$action=4;
		if($action == 4){
			$key  = 'banker_'.$action.'_'.$game['stream'];
			$list = DI()->redis->hGetAll($key);
			foreach($list as $k => $v){
				$data = json_decode($v, true);
				$uid  = $k;
				DI()->notorm->user->where('id = ?', $uid)->update(array('coin' => new NotORM_Literal("coin + {$data['deposit']}"),));
				$insert = array(
					"type"      => '1',
					"action"    => '24',
					"uid"       => $uid,
					"touid"     => $uid,
					"giftid"    => 0,
					"giftcount" => 1,
					"totalcoin" => $data['deposit'],
					"showid"    => 0,
					"addtime"   => $addtime,
				);
				
				DI()->notorm->user_coinrecord->insert($insert);
			}
		}
	}
	
	// 金花游戏：计算赢钱与输钱的位置
	protected function getJinhuaPosByBet($data, $value, $result, $percent_type)
	{
		$shuqian = $yingqian = [];
		// 如果三个投注位置的投注金额都是一样的 则随机返回
		if(($data[1] == $data[2]) && ($data[2] == $data[3])){
			DI()->logger->saveText("三个位置投注金额都是一样的".$result);
			
			return $result;
		}
		
		// 统计计算 赢钱 与 输钱 的位置
		$all    = $data[1] + $data[2] + $data[3];
		$total1 = $data[1] * 3;
		$total2 = $data[2] * 3;
		$total3 = $data[3] * 3;
		if($total1 > $all){
			$yingqian[] = 1;
		} elseif($total1 < $all){
			$shuqian[] = 1;
		}
		if($total2 > $all){
			$yingqian[] = 2;
		} elseif($total2 < $all){
			$shuqian[] = 2;
		}
		if($total3 > $all){
			$yingqian[] = 3;
		} elseif($total3 < $all){
			$shuqian[] = 3;
		}
		
		if($percent_type > 0){
			if($value){
				DI()->logger->saveText("干预：让用户赢钱：水池对比值".$value);
			}
			$pos = $yingqian[array_rand($yingqian)];
		} else{
			if($value){
				DI()->logger->saveText("干预：让用户输钱：水池对比值".$value);
			}
			$pos = $shuqian[array_rand($shuqian)];
		}
		
		return $pos;
	}
	
	// 获取百分比
	protected function getPlatformPercent($value)
	{
		// 其他情况的百分百
		//if(($value < 0) || ($value > 100000)){return 100;}
		
		// 获取游戏中的数字
		$percent = 0;
		$setting = $this->platformPercent();
		foreach($setting as $set){
			if(($set[0] <= $value) && ($set[1] >= $value)){
				$percent = $set[2];
				break;
			}
		}
		
		return $percent;
	}
	
	// 重新设置百分百
	protected function updatePlatformBetNumber($number)
	{
		$data = array('config' => new NotORM_Literal("config + {$number}"),);
		DI()->notorm->site_config->where('name=?', 'platform_total_amount')->update($data);
		/*if($number > 0){
			DI()->notorm->site_config->where('name=?', 'platform_total_amount_add')->update($data);
		} else{
			DI()->notorm->site_config->where('name=?', 'platform_total_amount_dec')->update($data);
		}*/
	}
	
	// 设置平台剩余金额的百分比：用于控制开奖
	protected function platformPercent()
	{
		return [
			// 开始值 结束值 百分比
			[500001, 99999999, 80],
			[300001, 500000, 40],
			[150001, 300000, 20],
			[50001, 150000, 10],
			[1, 50000, 0],
			[-999999, 0, 0],
			[-1499999, -1000000, -10],
			[-1999999, -1500000, -20],
			[-2499999, -2000000, -40],
			[-99999999999, -2500000, -80],
		
		];
		
	}
	
	
}
